$(function () {
    $('#showPassword').click(function () {
        var flag = $(this).attr('data-flag');
        $(this).attr('data-flag', flag == 'show' ? 'hide' : 'show');
        $(this).toggleClass('mdi-eye-off mdi-eye');
        $('input[name="password"]').attr('type', flag == 'show' ? 'text' : 'password');
    });

    getVersionInfo();

    // 是否记住密码
    /*var rem = $.cookie('remember');
    if(rem){
        $("#rememberMe").prop("checked",true);
        $("#username").val($.cookie("username"));
        $("#password").val($.cookie("password"));
    }*/

    // ie浏览器判断
    var ieFlag = IEVersion();
    if (ieFlag) {
        $.alert({
            title: '系统提示',
            content: '系统不支持ie浏览器，请使用最新版的谷歌浏览器或360浏览器！',
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'btn-primary',
                    action: function () {
                        $('.login-form input, .login-form button').attr('disabled', true);
                    }
                }
            }
        });
    }

    $('.login-label input').keyup(function (event) {
        if (event.keyCode == 13) {
            console.log('回车登录');
            submit();
        }
    });

    // 企微、密码登录切换
    $('.login-switch a').on('click', function () {
        $(this).hide().siblings().show();
        var type = $(this).data('type');
        if (type == 'qrCode') {
            $('#login_container').show();
            $('.login-form').hide();
            // 企微登录二维码初始化
            var wwLogin = new WwLogin({
                id: 'login_container',
                appid: 'wx7ee48e8ffb8b9a59',
                agentid: '1000035',
                redirect_uri: 'https%3A%2F%2Fwww.dcrm.cn%2FenterpriseWechatLogin',
                state: 'dcfl' + guid(),
                href: '',
                lang: 'zh',
            });
        } else {
            $('#login_container').hide();
            $('.login-form').show();
        }
    })

    var errorCode = $("#errorCode").val();
    if (errorCode) {
        var content = '';
        if (errorCode == 'L000001') {
            content = '企业微信未关联！';
        } else if (errorCode == 'L000002') {
            content = '请求未连接！';
        }
        $.alert({
            title: '提示',
            content: content,
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'btn-primary',
                    action: function () {
                        window.location.href = '/login';
                    }
                }
            }
        });
    }
});

//用于生成uuid
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
    return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
}

/**
 * 功能：记住密码
 * */

/*function save_cookies(){
    if($("#rememberMe").prop("checked")){
        var username = $("#username").val();
        var password = $("#password").val();

        $.cookie("remember","true",{expires:7});
        $.cookie("username",username,{expires:7 });
        $.cookie("password",password,{expires:7 });
    }else{
        $.cookie("remember","false",{expires:-1});
        $.cookie("username","",{ expires:-1 });
        $.cookie("password","",{ expires:-1 });
    }
};*/

/**
 * 功能：获取版本号
 * */
function getVersionInfo() {
    $.ajax({
        url: '/versionUpgrade/getVersionInfo',
        type: 'get',
        dataType: "json",
        success: function (data) {
            if (data.code == '000000') {
                $('#version').html('&nbsp;&nbsp;版本V<em>' + data.data.versionCode + '</em>');
            } else {
                console.log('错误代码：' + data.code);
            }
        },
        error: function (res) {
            console.log('数据请求失败，请重试！', res);
        }
    })
}

/**
 * 刷新验证码
 */
function refreshCaptcha() {
    var url = "/captcha/createVerifyImg?&d=" + Math.random();
    $("#captcha").attr("src", url);
}

/**
 * 登录验证
 */
function checkedData() {
    if (!$("#username").val()) {
        $.alert({
            title: '温馨提示',
            content: '用户名为空，请填写用户名！'
        });
        return false;
    }
    if (!$("#password").val()) {
        $.alert({
            title: '温馨提示',
            content: '密码为空，请填写密码！'
        });
        return false;
    }
    if (!$("#captchaBox").val()) {
        $.alert({
            title: '温馨提示',
            content: '验证码为空，请填写验证码！'
        });
        return false;
    }
    return true;
}

/**
 * 表单提交
 */
function submit() {
    // 登录时验证是否记住密码
    // save_cookies();
    var $btn = $('.login-form .btn-box button');

    if (checkedData()) {
        $btn.prop('disabled', true).html('<i class="mdi mdi-spin mdi-loading"></i> 登录中');
        var obj = {
            username: $("#username").val(),
            password: $("#password").val(),
            captcha: $("#captchaBox").val(),
            // rememberMe: $("#rememberMe").prop('checked'),
            rememberMe: false,
        };
        $.ajax({
            url: "/login",
            type: "POST",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            data: JSON.stringify(obj),
            async: false,
            success: function (data) {
                if (data.code === '000000') {
                    window.location.href = '/userLoginSuccess';
                } else if (data.code === 'P03001') {
                    $.alert({
                        title: '错误提醒',
                        content: '图形验证码错误，请重新输入！',
                        buttons: {
                            confirm: {
                                text: '确认',
                                action: function () {
                                    refreshCaptcha();
                                }
                            }
                        }
                    });
                } else if (data.code === 'PWD090') {
                    $.alert({
                        title: '错误提醒',
                        content: `${data.message}`,
                        buttons: {
                            confirm: {
                                text: '确认',
                                action: function () {
                                    loginPageShowResetPasswordModal();
                                }
                            }
                        }
                    });
                } else if (data.code === 'PWD080') {
                    $.alert({
                        title: '提醒',
                        content: `${data.message}`,
                        buttons: {
                            confirm: {
                                text: '确认',
                                action: function () {
                                    window.location.href = '/userLoginSuccess';
                                }
                            }
                        }
                    });
                } else {
                    $.alert({
                        title: '系统提醒',
                        content: (data.data || data.message),
                    });
                }
            },
            error: function (err) {
                $.alert({
                    title: '系统提醒',
                    content: '登录失败，请稍后再试！'
                });
                console.log(err);
            },
            complete: function () {
                setTimeout(function () {
                    $btn.prop('disabled', false).html('登录');
                }, 500);
            }
        })
    }
}


// ----------------------> 修改密码
function loginPageShowResetPasswordModal() {
    $("#oldPassword").val('');
    $("#newPassword").val('');
    $("#rePassword").val('');
    $("#editModel").modal('show');
}


function loginPageOldPasswordValidate() {
    loginPageResetPasswordValidate();
    var oldPassword = $.trim($("input[name=oldPassword]").val());
    $.ajax({
        url: "/account/oldPasswordValidate",
        type: "post",
        data: {
            oldPassword: oldPassword
        },
        success: function (data) {
            if (data.code === '000000') {
                $("#oldPasswordMsg").hide();
            } else {
                $("#oldPasswordMsg").show().html("原密码错误！");
            }
        }
    });
}

function loginPageResetPassword() {
    var oldPassword = $.trim($("input[name=oldPassword]").val());
    var userPassword = $.trim($("input[name=newPassword]").val());
    var rePassword = $.trim($("input[name=rePassword]").val());
    // var passwordReg=/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+={}:";'<>,.]).{8,16}/;
    // 必须包含一个字母及一个数字，其他位随意
    var passwordReg=/^(?=.*[a-z])(?=.*\d)[\s\S]{8,16}$/;
    if(!passwordReg.test(userPassword)){
        $.alert("密码需要包含字母、数字,长度控制在8-16");
        return ;
    }
    if (!oldPassword) {
        $.alert("请输入原密码！");
        return;
    }
    if (!userPassword) {
        $.alert("请输入新密码！");
        return;
    } else if (userPassword.length > 50) {
        $.alert("密码长度不能大于50个字符！");
        return;
    }
    if (oldPassword === userPassword) {
        $.alert("原密码和新密码相同！");
        return;
    }
    if (!rePassword) {
        $.alert("请输入确认密码！");
        return;
    }
    if (userPassword !== rePassword) {
        $.alert("两次输入密码不一致！");
        return;
    }
    $.ajax({
        url: "/account/resetPassword",
        type: "post",
        data: {
            userPassword: userPassword,
            oldPassword: oldPassword
        },
        success: function (data) {
            console.log(data)
            if (data.code === '000000') {
                window.location.href = '/userLoginSuccess';
            } else if (data.code === 'PSW001') {
                $.alert("原密码输入错误！");
            } else if (data.code === 'PSW002') {
                $.alert("密码太过简单，未通过验证！");
            } else {
                $.alert("保存失败！");
            }
        }
    });
}

/**
 * 修改密码 -- 确认密码校验
 */
function loginPageResetPasswordValidate() {
    var oldPassword = $("#oldPassword").val();
    var password = $("#newPassword").val();
    var rePassword = $("#rePassword").val();
    if (oldPassword !== password) {
        $("#passwordMsg").hide();
    } else {
        $("#passwordMsg").show().html("原密码和新密码相同！");
    }
    <!-- 对比两次输入的密码 -->
    if (password === rePassword) {
        $("#rePasswordMsg").hide();
    } else {
        $("#rePasswordMsg").show().html("两次输入密码不一致！");
    }
}

/**
 * 密码显示/隐藏
 * @param id
 * @param name
 */
function loginPagePwdEye(id, name) {
    var $div = $("#" + id);
    var flag = $($div).attr('data-flag');
    $($div).css('background-image', 'url("/images/login/password-' + flag + '.png")');
    $($div).attr('data-flag', flag === 'show' ? 'hide' : 'show');
    $('input[name="' + name + '"]').attr('type', flag === 'show' ? 'text' : 'password');
}
// ----------------------> 修改密码



// 验证ie浏览器
function IEVersion() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if (isIE || isIE11) {
        return true;
    } else {
        return false;
    }
}